<?php

class GridFieldEmailAction extends Extension {
    private static $allowed_actions = array(
        'email'
    );
    
    public function email($request) {
        $controller = $this->owner->getController();
        while($controller && $controller instanceof GridFieldDetailForm_ItemRequest) {
            $controller = $controller->getController();
        }

        if(!$request->getVar('field') || !$request->getVar('template') || !$request->getVar('subject')){
            $message = _t('GridFieldEmailAction.INVALID_PARAMETER', 'Invalid parameter for field, tempalte or subject.');
        }
        else if(!Email::is_valid_address($this->owner->record->getField($request->getVar('field')))){
            $message = _t('GridFieldEmailAction.INVALID_EMAIL', 'Invalid email address.');
        }
        else{
            $e = Email::create();
            $e->setTemplate($request->getVar('template'));
            $this->owner->record->SiteConfig = SiteConfig::current_site_config();
            $e->populateTemplate($this->owner->record);
            $e->setSubject($request->getVar('subject'));
            $e->setFrom($request->getVar('from'));
            $e->setTo($this->owner->record->getField($request->getVar('field')));
            if($e->send()){
                $message = _t('GridFieldEmailAction.SUCCESS_SENT_EMAIL', 'Email has been successfully sent.');
                if($this->owner->record->hasField('Sent')){
                    $this->owner->record->Sent += 1;
                    $this->owner->record->write(); 
                }
            }
            else{
                $message = _t('GridFieldEmailAction.ERROR_SEND_EMAIL', 'Error occur while sending email. Please check with our support. Thank you.');
            }
        }

        if($request->isAjax()) {
            return $message;
        } else {
            $form = $this->owner->ItemEditForm($this->owner->getGridField(), $request);
            $form->makeReadonly();
            $form->sessionMessage($message, 'success');
    
            $data = new ArrayData(array(
                'Backlink'     => $controller->Link(),
                'ItemEditForm' => $form
            ));
            $return = $data->renderWith($this->owner->getTemplate());
            return $controller->customise(array('Content' => $return));
        }
    }
}
